<?php
/**
 * Created by PhpStorm.
 * User: von
 * Date: 2017/12/4
 * Time: 10:31
 */

namespace backend\controllers;

use backend\models\Packageapply;
use backend\models\User;
use common\models\InstationMessage;
use common\models\Package;
use common\models\PackageInitiation;
use common\models\PackageLog;
use common\models\Responses;
use common\models\UserModel;
use yii\db\Exception;

class PackageApplyController extends BaseController{
    /*
     * 立项报告完成情况
     */
    public function actionJudgePackage(){
        $packageID = intval(\Yii::$app->request->get('package_id',1));
        $dataState = []; //返回状态 是否完善信息
        if (!(\Yii::$app->request->isPost)){
            //-------------------资产包基本情况-----------------

            $data = Packageapply::getPackageData($packageID);
            if (!empty($data) && $data['code']==200){
                $dataRes = $data['data']['res'];
                if (!empty($dataRes['title'])    || !empty($dataRes['type'])      ||
                    !empty($dataRes['creditor']) || !empty($dataRes['province'])  ||
                    !empty($dataRes['city'])     || !empty($dataRes['principal']) ||
                    !empty($dataRes['interest']) || !empty($dataRes['hushu'])     ||
                    !empty($dataRes['detail']) || !empty($dataRes['limit_collection'])  || !empty($dataRes['limit_collection'])){
                    $dataState['BasePackage'] = Responses::response200();
                }else{
                    $dataState['BasePackage'] = Responses::response400('请完善信息在提交');
                }
            }else{
                $dataState['BasePackage'] = Responses::response400('请完善信息在提交');
            }
            //-------------------流转 前期处理及维护-----------------
            $data = Packageapply::getPackageTransferHistory($packageID);
            $State = 0;
            if (!empty($data) && $data['code']==200){
                $dataRes = $data['data']['res'];
                foreach ($dataRes as $k => $v) {
                    if (empty($v['transfer_date']) && empty($v['transfer'])      &&
                        empty($v['content']) && empty($v['remark'])){
                        $State--;
                    }else{
                        $State=10000;
                    }
                }
                $dataState['PackageTransferHistory'] = $State>0?Responses::response200():Responses::response400('请完善信息在提交');
            }else{
                $dataState['PackageTransferHistory'] = Responses::response400('请完善信息在提交');
            }
            //-------------------卖家提供的信息资料-----------------
            $data = Packageapply::getPackageInitiation($packageID);
            $State = 0;
            if (!empty($data) && $data['code']==200){
                $dataRes = $data['data']['res'];
                foreach ($dataRes as $k => $v) {
                    if (empty($v['seller_files'])){
                        $State--;
                    }else{
                        $State=10000;
                    }
                }
                $dataState['PackageInitiation_seller_files'] = $State>0?Responses::response200():Responses::response400('请完善信息在提交');
            }else{
                $dataState['PackageInitiation_seller_files'] = Responses::response400('请完善信息在提交');
            }
            //-------------------资产成交的期限和成交方式-----------------
            $State = 0;
            if (!empty($data) && $data['code']==200){
                $dataRes = $data['data']['res'];
                foreach ($dataRes as $k => $v) {
                    if (empty($v['deal_method'])){
                        $State--;
                    }else{
                        $State=10000;
                    }
                }
                $dataState['PackageInitiation_deal_method'] = $State>0?Responses::response200():Responses::response400('请完善信息在提交');
            }else{
                $dataState['PackageInitiation_deal_method'] = Responses::response400('请完善信息在提交');
            }
            //-------------------当地共同处置资产包的合作伙伴情况-----------------
            $State = 0;
            if (!empty($data) && $data['code']==200){
                $dataRes = $data['data']['res'];
                foreach ($dataRes as $k => $v) {
                    if (empty($v['partners'])){
                        $State--;
                    }else{
                        $State=10000;
                    }
                }
                $dataState['PackageInitiation_partners'] = $State>0?Responses::response200():Responses::response400('请完善信息在提交');
            }else{
                $dataState['PackageInitiation_partners'] = Responses::response400('请完善信息在提交');
            }
            //-------------------当地司法环境对所立项目的法律支持分析-----------------
            $State = 0;
            if (!empty($data) && $data['code']==200){
                $dataRes = $data['data']['res'];
                foreach ($dataRes as $k => $v) {
                    if (empty($v['law'])){
                        $State--;
                    }else{
                        $State=10000;
                    }
                }
                $dataState['PackageInitiation_law'] = $State>0?Responses::response200():Responses::response400('请完善信息在提交');
            }else{
                $dataState['PackageInitiation_law'] = Responses::response400('请完善信息在提交');
            }
            //-------------------卖家报价、及未来价格可谈判空间-----------------
            $State = 0;
            if (!empty($data) && $data['code']==200){
                $dataRes = $data['data']['res'];
                foreach ($dataRes as $k => $v) {
                    if (empty($v['bargain'])){
                        $State--;
                    }else{
                        $State=10000;
                    }
                }
                $dataState['PackageInitiation_bargain'] = $State>0?Responses::response200():Responses::response400('请完善信息在提交');
            }else{
                $dataState['PackageInitiation_bargain'] = Responses::response400('请完善信息在提交');
            }
            //-------------------团队组成-----------------
            $State = 0;
            if (!empty($data) && $data['code']==200){
                $dataRes = $data['data']['res'];
                foreach ($dataRes as $k => $v) {
                    if (!empty($v['leader'])||!empty($v['other_team_notes'])||!empty($v['pre_evaluation'])||!empty($v['due_diligence'])){
                        $State=10000;
                    }else{
                        $State--;
                    }
                }
                $dataState['PackageInitiation_team'] = $State>0?Responses::response200():Responses::response400('请完善信息在提交');
            }else{
                $dataState['PackageInitiation_team'] = Responses::response400('请完善信息在提交');
            }
            //-------------------工作计划-----------------
            $data = Packageapply::getPackagePlan($packageID);
            $State = 0;
            if (!empty($data) && $data['code']==200){
                $dataRes = $data['data']['res'];
                foreach ($dataRes as $k => $v) {
                    if (!empty($v['stage'])||!empty($v['job'])){
                        $State=10000;
                    }else{
                        $State--;
                    }
                }
                $dataState['PackageInitiationPlan'] = $State>0?Responses::response200():Responses::response400('请完善信息在提交');
            }else{
                $dataState['PackageInitiationPlan'] = Responses::response400('请完善信息在提交');
            }
            //-------------------团队收益分配-----------------
            $data = Packageapply::getPackageInitiationIncome($packageID);
            $State = 0;
            if (!empty($data) && $data['code']==200){
                $dataRes = $data['data']['res'];
                foreach ($dataRes as $k => $v) {
                    if (empty($v['stage'])||empty($v['profit'])){
                        $State--;
                    }else{
                        $State=10000;
                    }
                }
                $dataState['PackageInitiationIncome'] = $State>0?Responses::response200():Responses::response400('请完善信息在提交');
            }else{
                $dataState['PackageInitiationIncome'] = Responses::response400('请完善信息在提交');
            }
            //-------------------获取预评估表完成情况-----------------
            $data = Packageapply::desireProject($packageID);
            $State = 0;
            if (!empty($data) && $data['code']==200){
                $dataState['yupinggucount'] = $data['data']['res'];
            }else{
                $dataState['yupinggucount'] = Responses::response400('请完善信息在提交');
            }
            //-------------------获取预评估表完成情况----折扣率/预估投资回报率-------------
            $packageData =  PackageController::getAllCalculate($packageID);
            if (!empty($packageData)){
                $dataState['zkl'] = $packageData['zkl'];
                $dataState['evaluationHBB']= $packageData['evaluationHBB'];
            }else{
                $dataState['zkl'] = 0;
                $dataState['evaluationHBB'] = 0;
            }
            //------------------- 申请立项理由-------------
            $dataState['reasonData'] = (new \yii\db\Query())->from(PackageInitiation::tableName())->where(['=','package_id',$packageID])->one()['reason'];
            return $this->renderPartial('index',$dataState);
        }else{
            /*
             * 保存立项申请 并发送立项审核消息给管理员
             */
            //-------------------申请立项理由-----------------
            $reasonText = \Yii::$app->request->post('reasonText','');
            $state      = \Yii::$app->request->post('state',\Yii::$app->params['LIXIANGSHENPIN']);
            $packageID  = \Yii::$app->request->post('package_id',1);

            $UpState = Packageapply::updatePackageInitiationReason($packageID,$reasonText,$state);
            //--------------------立项成功 发送消息----------------------
            if ($UpState['code']==200){
                //-----log--------flt--start--
                $packageLog = new PackageLog();
                $packageLog->package_id = $packageID;
                $packageLog->created_at = date('Y-m-d H:i:s');
                $packageLog->user_id = \Yii::$app->user->getId();
                $packageLog->log = "新增申请立项";
                $re = $packageLog->save();
                if (!$re) {
                    throw new Exception('资产包日志保存失败');
                }
                //-----log--------flt--end--
                $pack_name    = (new \yii\db\Query())->from(Package::tableName())->where(['=','id',$packageID])->one()['title'];
                //审核员角色
                $user_id  = array_column(json_decode(User::getRolesUser('Projectapprovalspecialist'),true)['data']['res'],'user_id');

                $sender_id = \Yii::$app->user->getId();
                $applicant_name = (new \yii\db\Query())->from(User::tableName())->where(['=','id',$sender_id])->one()['realname'];
                $applicant_bumen = (new \yii\db\Query())->from(User::tableName())->leftJoin('auth_item as ai','user.department = ai.name')->where(['=','id',$sender_id])->one()['description'];
                $application    = "立项审批";
                $messageArr   = [
                    'pack_name'=>$pack_name,
                    'applicant'=>$applicant_bumen.'-'.$applicant_name,
                    'application'=>$application,
                    'applicationReason'=>$reasonText
                ];
                $package_id= intval($packageID);
                //如果没有审核管理员则不发送数据
                if (!empty($user_id) && is_array($user_id)){
                    $data = [];
                    $data['sender'] = \Yii::$app->user->getId();//发件人id
                    $data['package_project_id'] = $package_id;//资产包id
                    $data['is_package'] = 1;//是否是资产包/1是资产包/2是项目
                    $data['message_val'] = json_encode($messageArr); //消息内容 json

                    $data['user_id'] = $user_id;//收件人id
                    $data['message_state'] = \Yii::$app->params['UNREND'];//消息状态 0未阅读 1已阅读
                    $data['message_group'] = \Yii::$app->params['DAI_SHENPIN_LX']; //消息分类 1待审批提醒 2审批反馈 3关注更新*/

                    $param = [];
                    $param['where_sender'] = \Yii::$app->user->getId();//发件人id
                    $param['where_is_package'] = 1;//是否是资产包/1是资产包/2是项目
                    $param['where_package_project_id'] =  $package_id;//资产包id
                    $param['where_message_group'] =  \Yii::$app->params['DAI_SHENPIN_LX'];//资产包id 消息分类 1待审批提醒 2审批反馈 3关注更新
                    $messageState = InstationMessage::saveMessage($param,$data);
                }else{
                    $messageState['code']=200;
                    $messageState['message']='审批成功,无审核管理员,没发送消息';
                }
                //--------------------立项成功 发送消息----------------------
                if(!empty($messageState) && $messageState['code']==200){
                    return json_encode($UpState);
                }else{
                    return json_encode(Responses::response400('向管理员发送消息失败'));
                }
                return json_encode(Responses::response400('更新失败'));
            }
            return json_encode(Responses::response400('更新失败'));
        }

    }

    /*
     *申请访问
     */
    public function actionAccessApply(){
        if (\Yii::$app->request->isAjax){
            $data['package_id'] = intval(\Yii::$app->request->post('packageId',1));
            $data['title'] = \Yii::$app->request->post('title','');
            $data['group'] = intval(\Yii::$app->request->post('group',1));
            $data['reason'] = \Yii::$app->request->post('shenqingFWNote','');
            $data['proposer'] = \Yii::$app->user->getId();
            //----审批人id----
            $user_id='';
            $pack_name    = $data['title'];
            $leaderid = 0;
            if ($data['group']==1){
                $userData = (new \yii\db\Query())->from('package_initiation')->where(['=','package_id',$data['package_id']])->one();
                $leaderTemp = explode(',',$userData['leader']);
                if (array_key_exists('0',$leaderTemp)){
                    if(!empty($leaderTemp[0]))     $leaderid = $leaderTemp[0];
                }
                if (array_key_exists('1',$leaderTemp)){
                    if(!empty($leaderTemp[1]))   $leaderid = $leaderTemp[1];
                }

                if (empty($leaderid)){
                    $leaderid = $userData['leader'];
                }

                if (empty($leaderid)){
                    $userData = (new \yii\db\Query())->from('package')->where(['=','id',$data['package_id']])->one();
                    if (!empty($userData['owner'])){
                        $user_id = [$userData['owner']];
                    }
                }else{

                    $user_id = [$leaderid];
                }
            }else{
                $userData = (new \yii\db\Query())->from('project_team')->where(['=','project_id',$data['package_id']])->one();
                if (!empty($userData['owner'])){
                    $user_id = [$userData['owner']];
                }else{
                    $userPIData = (new \yii\db\Query())->from('package_initiation')->leftJoin('project','package_initiation.package_id = project.package_id')->where(['=','project.id',$data['package_id']])->one();
                    if (!empty($userPIData['leader'])){
                        $leaderTemp = explode(',',$userPIData['leader']);
                        if (array_key_exists('0',$leaderTemp)){
                            if(!empty($leaderTemp[0]))     $leaderid = $leaderTemp[0];
                        }
                        if (array_key_exists('1',$leaderTemp)){
                            if(!empty($leaderTemp[1]))   $leaderid = $leaderTemp[1];
                        }

                        if (empty($leaderid)){
                            $leaderid = $userPIData['leader'];
                        }

                        $user_id = [$leaderid];
                    }else{
                        $userPData = (new \yii\db\Query())->from('package')->leftJoin('project','package.id = project.package_id')->where(['=','package.id',$data['package_id']])->one();
                        $user_id = [$userPData['owner']];
                    }
                }
            }
            $data['user_id'] = $user_id;
            $data['is_package'] = \Yii::$app->request->post('is_package',1);//是否是资产包/1是资产包/2是项目
            //----审批人id----
            $accessApplyState = Packageapply::saveFWApply($data);
            $accessApplyState = json_decode($accessApplyState,true);
            if (!empty($accessApplyState) && $accessApplyState['code']==200){
                //--------------------申请访问 发送消息----------------------
                    //申请立项发送消息
                    $sender_id = \Yii::$app->user->getId();
                    $applicant_name = (new \yii\db\Query())->from(User::tableName())->where(['=','id',$sender_id])->one()['realname'];
                    $applicant_bumen = (new \yii\db\Query())->from(User::tableName())->leftJoin('auth_item as ai','user.department = ai.name')->where(['=','id',$sender_id])->one()['description'];
                    $application    = "访问审批";
                    $messageArr   = [
                        'pack_name'=>$pack_name,
                        'applicant'=>$applicant_bumen.'-'.$applicant_name,
                        'application'=>$application,
                        'applicationReason'=>$data['reason']
                    ];
                    $package_id= intval($data['package_id']);
                //如果没有审核管理员则不发送数据
                if (!empty($user_id) && is_array($user_id)){
                        $data = [];
                        $data['sender'] = \Yii::$app->user->getId();//发件人id
                        $data['package_project_id'] = $package_id;//资产包id
                        $data['is_package'] = \Yii::$app->request->post('is_package',1);//是否是资产包/1是资产包/2是项目
                        $data['message_val'] = json_encode($messageArr); //消息内容 json

                        $data['user_id'] = $user_id;//收件人id
                        $data['message_state'] = \Yii::$app->params['UNREND'];//消息状态 0未阅读 1已阅读
                        $data['message_group'] = \Yii::$app->params['DAI_SHENPIN_FW']; //消息分类 1待审批提醒 2审批反馈 3关注更新*/

                        $param = [];
                        $param['where_sender'] = \Yii::$app->user->getId();//发件人id
                        $param['where_is_package'] = \Yii::$app->request->post('is_package',1);//是否是资产包/1是资产包/2是项目
                        $param['where_package_project_id'] =  $package_id;//资产包id
                        $param['where_message_group'] =  \Yii::$app->params['DAI_SHENPIN_FW'];//资产包id 消息分类 1待审批提醒 2审批反馈 3关注更新
                        $messageState = InstationMessage::saveMessage($param,$data);
                    }else{
                        $messageState['code']=200;
                        $messageState['message']='审批成功,无审核管理员,没发送消息';
                    }
                    if(!empty($messageState) && $messageState['code']==200){
                        return json_encode(Responses::response200('',1,'申请访问成功，向管理员发送消息成功'));
                    }else{
                        return json_encode(Responses::response400('申请访问成功，向管理员发送消息失败'));
                    }
                    //--------------------申请访问 发送消息----------------------
                return json_encode(Responses::response200('',1,'申请访问成功，向管理员发送消息成功'));
            }
            return json_encode(Responses::response400("申请访问失败出错"));
        }
        return json_encode(Responses::response400("申请访问失败出错"));
    }
}
